<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据类型_名称" prop="docTypeName">
        <el-input v-model="queryParams.docTypeName" placeholder="请输入单据类型_名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['purchase:purchase:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['purchase:purchase:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['purchase:purchase:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['purchase:purchase:export']">导出</el-button>
      </el-col>

      <el-button size="mini" plain type="primary" icon="el-icon-delete" @click="zhongzhi" :disabled="single">
        强制终止</el-button>



      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="请购单ID,主键" align="center" prop="id" />
      <el-table-column label="单据类型_名称" align="center" prop="docTypeName" />
      <el-table-column label="请购单号" align="center" prop="purchaseRequestNo" />
      <el-table-column label="单据状态" align="center" prop="docStatus" :formatter="formatdocStatus" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="formatAuditStatus" />
      <el-table-column label="来源单据" align="center" prop="sourceDoc" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:purchase:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:purchase:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="zhongzhi(scope.row)"
            :class="{ 'hidden': !isButtonEnabled(scope.row) }" :disabled="!isButtonEnabled(scope.row)">
            强制终止</el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />



    <el-dialog title="终止" :visible.sync="zhongzhiopen" width="30%" :before-close="handleClose">

      <el-form label-width="100px" :model="this.from3">
        <el-form-item label="终止原因">
          <el-input type="textarea" :rows="3" placeholder="请输入终止原因" v-model="from3.reason">
            <!--            //后端前端交互数据的依据就是名称-->
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="zhongzhis">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="审核记录表" :visible.sync="jiludialog" width="80%" :before-close="handleClose">
      <el-table v-loading="loading" :data="jiluList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="记录ID" align="center" prop="id" />
        <el-table-column label="业务ID" align="center" prop="businessId" />
        <el-table-column label="业务类型" align="center" prop="businessType" />
        <!--        <el-table-column label="审批节点" align="center" prop="approvalNode" />-->
        <el-table-column label="审批人" align="center" prop="approver" />
        <el-table-column label="审批时间" align="center" prop="approvalTime" />
        <el-table-column label="审批结果" align="center" prop="result" :formatter="formatAuditStatus" />
        <el-table-column label="审批意见" align="center" prop="opinion" />
        <el-table-column label="上一级审批人" align="center" prop="previousApprover" />
        <el-table-column label="下一级审批人" align="center" prop="nextApprover" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
        <el-table-column label="删除状态" align="center" prop="deleted" />
        <el-table-column label="流程状态" align="center" prop="processStatus" />
      </el-table>
    </el-dialog>













    <el-dialog title="审批" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">

      <el-form label-width="100px" :model="form2">
        <el-form-item label="审批意见">
          <el-input type="textarea" :rows="3" placeholder="请输入审批意见" v-model="form2.opinion">
          </el-input>
        </el-form-item>

        <el-form-item label="审批结果">
          <el-radio-group v-model="choices">
            <el-radio label="agree">同意</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateshenhe">确 定</el-button>
      </span>
    </el-dialog>



    <!-- 添加或修改请购单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据类型_名称" prop="docTypeName">
          <el-input v-model="form.docTypeName" placeholder="请输入单据类型_名称" />
        </el-form-item>
        <el-form-item label="请购单号" prop="purchaseRequestNo">
          <el-input v-model="form.purchaseRequestNo" placeholder="请输入请购单号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="来源单据" prop="sourceDoc">
          <el-input v-model="form.sourceDoc" placeholder="请输入来源单据" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->



        <div slot="footer" class="dialog-footer" label-width="150">
          <el-button type="primary" @click="saveForm" :class="{ 'hidden': baocun }" :disabled="baocun">保存</el-button>
          <el-button type="primary" v-if="isEditMode" @click="auditForm">审核并新增</el-button>
          <el-button type="primary" :class="{ 'hidden': shenhe }" v-else @click="showApprovalDialog"
            :disabled="shenhe">仅审核</el-button>

          <el-button type="primary" @click="tijiao" v-if="isEditMode">提交并新增</el-button>
          <el-button type="primary" :class="{ 'hidden': tijiaoaudit }" :disabled="tijiaoaudit" v-else
            @click="updatetijiao">仅提交</el-button>
          <el-button size="mini" plain type="primary" icon="el-icon-delete" @click="jilu" :disabled="single">
            查看历史记录</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPurchase,
  getPurchase,
  delPurchase,
  addPurchase,
  updatePurchase,
  updatetijiao, updateshenhe, shenhe, tijiao, baocun, zhongzhi, jilu
} from "@/api/purchase/purchase";

export default {
  name: "Purchase",
  data() {
    return {
      uid: '',
      tijiaoaudit: true,
      shenhe: true,
      baocun: false,
      form2: {},
      dialogVisible: false,//审核弹出框 同意或拒绝
      isDisabled: false, // 设置为true禁用按钮      // 遮罩层
      isEditMode: true,
      choices: '',
      choice: '', //选中 0拒绝 1同意
      opinion: '', //审核意见
      from3: {},
      zhongzhiid: [],
      zhongzhiopen: false,
      jiludialog: false,
      jiluList: [],







      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请购单管理表格数据
      purchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        docTypeName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        purchaseRequestNo: [
          { required: true, message: "请购单号不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {


    showApprovalDialog() {
      this.dialogVisible = true
    },


    updatetijiao() {
      console.log(this.uid);
      updatetijiao(this.uid).then(response => {
        this.form = response.data;
        this.getList();
      });
    },
    updateshenhe() {
      console.log(this.uid);
      console.log(this.form2.opinion);
      if (this.form2.opinion === '' || this.form2.opinion == null) {
        this.$message.warning('请输入审批意见')
        return
      }
      // 提交审批逻辑
      console.log('提交审批:', this.opinion)
      // 根据结果执行不同操作
      if (this.choices === 'agree') {
        this.choice = 1
      } else {
        this.choice = 0
      }
      // 关闭弹窗
      this.dialogVisible = false
      // 重置表单
      this.resetForm()
      console.log(this.choice);
      updateshenhe(this.uid, this.form2.opinion, this.choice).then(response => {
        this.getList();
      }).catch(error => {
        console.log(error.response.data.msg); // 失败时："审核失败"
      });
    },
    handleClose(done) {
      // 关闭前的回调
      this.$confirm('确定要关闭审批窗口吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done()
        this.resetForm()
      }).catch(() => { })
    },
    resetForm() {
      this.approvalForm = {
        opinion: '',
        result: 'agree'
      }
    },

    saveForm() {
      this.form.auditStatus = 0
      console.log('保存表单:', this.form);
      baocun(this.form).then(response => {
        this.managementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.$message.success('保存成功');
    },

    auditForm() {
      this.form.auditStatus = 2
      console.log('审核表单:', this.form);
      shenhe(this.form).then(response => {
        this.managementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.$message.info('已提交审核');
    },
    tijiao() {
      this.form.auditStatus = 1
      console.log('提交表单:', this.form);
      tijiao(this.form).then(response => {
        this.managementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.
        this.$message.success('审核成功');
    },



    formatAuditStatus(row, column, cellValue) {
      const statusMap = {
        0: '草稿',
        1: '待审核',
        2: '已审核',
        3: '拒绝',
        4: '审核完成',
        5: '强制终止'
      }
      return statusMap[cellValue] || '未知状态'
    },
    formatdocStatus(row, column, cellValue) {
      const statusMap = {
        0: '待提交',
        1: '已提交',
        2: '审核完成',
        3: '已终止'
        // 其他状态码可继续扩展...
      }
      return statusMap[cellValue] || '未知状态'
    }
    ,


    zhongzhi(row) {
      alert(1)
      const ids = row.id || this.ids;
      console.log(ids);
      this.zhongzhiid = ids;

      this.reset();
      this.zhongzhiopen = true;
    },




    zhongzhis() {
      this.$modal.confirm(`是否确认终止请购单管理编号为"${this.zhongzhiid}"的数据项？`)
        .then(() => {  // 使用箭头函数保持this指向
          // 确保zhongzhi函数是可访问的，且参数正确
          return zhongzhi(this.zhongzhiid, this.from3.reason);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("强制终止成功");
        })
        .catch(() => {
          // 最好在这里添加错误处理
        });
    },
    isButtonEnabled(order) {
      return order.auditStatus === 0 || order.auditStatus === 1;
    },
    async jilu() {
      this.loading = true;
      try {
        const data = await jilu(this.uid);
        console.log(data);
        this.jiluList = data;
        this.jiludialog = true;

        // 更新UI状态
        this.open = false;
        this.jiludialog = true;

        // 如果需要刷新列表
        this.getList();
      } catch (error) {
        console.error('获取审批记录失败:', error);
        this.$message.error('获取审批记录失败');
      } finally {
        this.loading = false;
      }
    },



    /** 查询请购单管理列表 */
    getList() {
      this.loading = true;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        docTypeName: null,
        purchaseRequestNo: null,
        docStatus: null,
        remark: null,
        creator: null,
        createTime: null,
        auditStatus: null,
        sourceDoc: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isEditMode = true;
      this.baocun = false;

      this.reset();
      this.open = true;
      this.title = "添加请购单管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isEditMode = false
      this.baocun = true
      this.reset();
      const id = row.id || this.ids
      this.uid = id;

      getPurchase(id).then(response => {
        this.form = response.data;
        console.log(this.form);


        if (this.form.auditStatus === 1) {
          this.shenhe = false
          this.tijiaoaudit = true;

        }
        if (this.form.auditStatus === 2) {
          this.tijiaoaudit = true;
          this.shenhe = true

        }
        //提交
        if (this.form.auditStatus === 0) {
          this.tijiaoaudit = false;
        }
        this.open = true;
        this.title = "修改请购单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除请购单管理编号为"' + ids + '"的数据项？').then(function () {
        return delPurchase(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.hidden {
  display: none;
}
</style>
